package com.chenfwind.serviceImpl;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.chenfwind.IDao.BookMapper;
import com.chenfwind.IDao.CommentMapper;
import com.chenfwind.IDao.OwnerMapper;
import com.chenfwind.IDao.TrajectoryMapper;
import com.chenfwind.IDao.UserTrackMapper;
import com.chenfwind.common.Constant;
import com.chenfwind.common.StringUtils;
import com.chenfwind.domain.Book;
import com.chenfwind.domain.Comment;
import com.chenfwind.domain.Owner;
import com.chenfwind.domain.Trajectory;
import com.chenfwind.domain.UserTrack;
import com.chenfwind.service.CommentService;

@Service("commentService")
public class CommentServiceImpl implements CommentService{
	
	@Autowired
	private CommentMapper commentDao;
	
	@Autowired
	private BookMapper bookDao;
	
	@Autowired
	private OwnerMapper ownerDao;
	
	@Autowired
	private TrajectoryMapper trajectoryDao;
	
	@Autowired
	private UserTrackMapper userTrackDao;
	
	@Transactional
	public void changeCommentStatusByCommentId(String commentId,String status){
		
		if (Constant.COMMENT_STATUS_SUCCESS.equals(status)) {
			Comment comment = commentDao.selectByPrimaryKey(commentId);
			comment.setStatus(Integer.valueOf(status));
			commentDao.updateByPrimaryKeySelective(comment);
			
			Book book = new Book();
			book.setId(comment.getBookId());
			book.setStatus(1);
			bookDao.updateByPrimaryKeySelective(book);
			
			//更新owner用户的拥有着
			ownerDao.updateOwnerByBookId(0, comment.getBookId());

			Owner owner = new Owner();
			owner.setId(StringUtils.genUUID());
			owner.setBookId(comment.getBookId());
			owner.setUserId(comment.getUserId());
			owner.setPraentUserId(comment.getMasterUserId());
			owner.setStatus(1);
			owner.setUpdateTiem(new Date());
			ownerDao.insertSelective(owner);
			
			//轨迹
			trajectoryDao.updateStatusByBookId(comment.getBookId(),0);
			
			Trajectory tra = new Trajectory();
			tra.setId(StringUtils.genUUID());
			tra.setBookId(comment.getBookId());
			tra.setUserId(comment.getUserId());
			tra.setStatus(1);
			tra.setRank(trajectoryDao.selectMaxRank(comment.getBookId()) + 1);
			UserTrack userTrack = userTrackDao.selectByUserIDAndStatus(comment.getUserId(), 1);
			tra.setX(userTrack.getX());
			tra.setY(userTrack.getY());
			trajectoryDao.insertSelective(tra);
				
		} else {
			commentDao.updateStatusByID(commentId,2);
		}
	}
	
	@Transactional
	public List<Comment> findCommentByUserID(String userId) {
		return commentDao.selectByUserId(userId);
	}
	
	@Transactional
	public int save(Comment comment){
		return commentDao.insertSelective(comment);
	}
}
